<template>
  <div class="app-container">


    <el-form ref="queryForm" :model="queryParams" :inline="true" label-width="120px">

      <el-form-item label="来源">
        <el-select v-model="queryParams.source" clearable placeholder="请选择来源" style="width:100%">
          <el-option
            v-for="(item, index) in ['公众号','网页']"
            :key="index"
            :label="item"
            :value="item"
          />
        </el-select>
      </el-form-item>

      <!-- 来源名称 -->
      <el-form-item label="来源名称" prop="search_name">
        <el-input v-model="queryParams.search_name" placeholder="来源名称" clearable size="small" />
      </el-form-item>

      <!-- 文章标题搜索 -->
      <el-form-item label="文章标题" prop="title">
        <el-input v-model="queryParams.title" placeholder="请输入文章标题" clearable size="small" />
      </el-form-item>

      <!-- 新闻时间区间 格式化要Y-m-d -->
      <el-form-item label="新闻时间区间" prop="post_time">
        <el-date-picker v-model="queryParams.post_time" type="daterange" range-separator="至" format="yyyy-MM-dd" value-format="yyyy-MM-dd" start-placeholder="开始日期" end-placeholder="结束日期" />
      </el-form-item>

      <!-- 分数搜索 -->
      <el-form-item label="分数搜索" prop="score">
        <el-input v-model="queryParams.score" placeholder="分数搜索" clearable size="small" />
      </el-form-item>

      <!-- 是否banner 用 select 支持清除 -->
      <el-form-item label="是否banner" prop="is_rec">
        <el-select v-model="queryParams.is_rec" clearable placeholder="请选择是否banner" style="width:100%">
          <el-option :value="1" label="是" />
          <el-option :value="0" label="否" />
        </el-select>
      </el-form-item>

      <!-- 是否发布 用 select 支持清除 -->
      <el-form-item label="是否发布" prop="publish">
        <el-select v-model="queryParams.publish" clearable placeholder="请选择是否发布" style="width:100%">
          <el-option :value="1" label="是" />
          <el-option :value="0" label="否" />
        </el-select>
      </el-form-item>

      <el-form-item label="文章分类">
        <el-select v-model="queryParams.cate_id" clearable placeholder="请选择新闻分类" style="width:100%">
          <el-option
            v-for="(item, index) in cate_list"
            :key="index"
            :label="item.name"
            :value="item.id"
          />
        </el-select>
      </el-form-item>



      <el-form-item>
        <el-button type="primary" icon="el-icon-search" size="mini" @click="handleQuery">搜索</el-button>
        <el-button icon="el-icon-refresh" size="mini" @click="resetQuery">重置</el-button>
      </el-form-item>
    </el-form>

    <el-button type="primary" icon="el-icon-plus" @click="openAdd({}, '添加')" >新增</el-button>

    <!-- 添加分类状态tabs -->
    <el-tabs v-model="activeTab" @tab-click="handleTabClick" >
      <el-tab-pane label="全部" name="all"></el-tab-pane>
      <!-- <el-tab-pane label="已分类" name="categorized"></el-tab-pane> -->
      <el-tab-pane label="未分类资讯" name="uncategorized"></el-tab-pane>
    </el-tabs>

    <el-table
      v-loading="loading"
      :default-sort="{prop:'post_time', order: 'descending'}"
      :data="list"
      style="width: 100%;"
      stripe
      highlight-current-row
      @sort-change="sortChange"
      @selection-change="handleSelectionChange"
    >
      <!-- <el-table-column type="selection" align="center" width="50" /> -->
      <el-table-column label="ID" align="center" prop="id" sortable="custom" />
      <el-table-column label="来源" align="center" prop="source" />
      <el-table-column label="来源名称" align="center" prop="search_name" />
      <el-table-column label="文章标题" align="center" prop="title" />
      <el-table-column label="文章分类" align="center" prop="cate_name" />

      <!-- 超链接 -->
      <el-table-column label="超链接" align="center" prop="path">
        <template v-slot="scope">
          <el-button v-if="scope.row.path" type="primary" icon="el-icon-document" circle @click="toUrl(scope.row.path,$event)" />
        </template>
      </el-table-column>

      <!--
      <el-table-column label="路径" align="center" prop="path" show-overflow-tooltip width="250">
        <template v-slot="scope">
          <el-col :span="20" style="overflow: hidden;">{{ scope.row.path }}</el-col>
          <el-row v-if="scope.row.path" type="flex" justify="flex-start">
            <el-col><el-button size="mini" type="primary" icon="el-icon-document" circle @click="handleCopy(scope.row.path,$event)" /></el-col>
          </el-row>

        </template>
      </el-table-column>
      -->

      <el-table-column label="封面图片" align="center">
        <template slot-scope="scope">
          <el-image
            v-if="scope.row.cover_url"
            referrer-policy="no-referrer"
            :src="scope.row.cover_url"
            style="height: 50px"
            :preview-src-list="[scope.row.cover_url]"
          />
        </template>
      </el-table-column>

      <el-table-column label="新闻日期" align="center" prop="post_time" sortable="custom" />
      <el-table-column label="分数" align="center" prop="score" sortable="custom" />

      <el-table-column label="标签" align="center" prop="tags" width="200">
        <template v-slot="scope">
          <div v-if="scope.row.tags && scope.row.tags.length > 0" type="success">
            <el-tag style="margin-right: 5px;margin-bottom: 5px;" v-for="tag in scope.row.tags" :key="tag" type="success">{{ tag }}</el-tag>
          </div>
        </template>
      </el-table-column>

      <el-table-column label="资讯推荐" align="center" prop="is_rec">
        <template v-slot="scoped">
          <el-tag v-if="scoped.row.is_rec == 1" type="success">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
          <!--          <el-switch-->
          <!--            v-model="scoped.row.is_rec"-->
          <!--            :active-value="1"-->
          <!--            :inactive-value="0"-->
          <!--          />-->
        </template>
      </el-table-column>

      <el-table-column label="栏目推荐" align="center" prop="is_rec2">
        <template v-slot="scoped">
          <el-tag v-if="scoped.row.is_rec2 == 1" type="success">是</el-tag>
          <el-tag v-else type="danger">否</el-tag>
        </template>
      </el-table-column>

      <el-table-column label="入库时间" align="center" prop="created_at" sortable="custom" />

      <el-table-column label="操作" align="center" class-name="small-padding fixed-width" width="250">
        <template v-slot="scope">
          <!-- :disabled="scope.row.id === 1" -->

          <!-- 根据 scope.row.publish 显示不同的按钮 发布 or 停止 -->
          <el-button v-if="scope.row.publish == 1" size="mini" type="warning" @click="publish(scope.row, 0)">停止</el-button>
          <el-button v-else size="mini" type="primary" @click="publish(scope.row, 1)">发布</el-button>

          <el-button v-action="'news@update'" size="mini" type="primary" @click="openAdd(scope.row, '编辑')">编辑</el-button>
          <el-button v-action="'news@delete'" size="mini" type="danger" @click="delPort(scope.row)">删除</el-button>
        </template>
      </el-table-column>
    </el-table>
    <pagination
      v-show="total > 0"
      :total="total"
      :page.sync="queryParams.page"
      :limit.sync="queryParams.limit"
      @pagination="getList"
    />
    <!-- 新增/修改 -->
    <Add :open.sync="open1" :title="title1" :cate_list="cate_list" :form="form1" @getList="getList" @refresh="newList()" />
  </div>
</template>
<style>
.el-input__inner {
  width: 90%;
}

.el-input__suffix {
  right: 10%;
}
</style>
<script>
import { deleteNews, editNews, newsList } from '@/api/externalGoods'
import { mapGetters } from 'vuex'
import Add from './Add'
import clip from '@/utils/clipboard'
import { businesstypeList } from '@/api/basics' // use clipboard directly
import { publishNews } from '@/api/externalGoods'

export default {
  name: 'jsNewsIndex',
  components: {
    Add
  },
  data() {
    return {
      // 遮罩层
      loading: true,
      open: false,
      title: '',
      // 总条数
      total: 0,
      // 表格数据
      list: [],
      portConfig: [],
      info: '',
      // 查询参数
      queryParams: {
        page: 1,
        limit: 10,
        is_jiangsu_zone: 1,
        title: undefined
      },
      options1: [],
      props: { checkStrictly: true, label: 'name', value: 'id' },
      category_ids: [],
      form: {},
      show: false,
      ids: [],
      multiple: false,
      dialogImageUrl: '',
      dialogVisible: false,
      importHeaders: { authorization: 'Bearer ' + this.token },
      fileList: [],
      url: undefined,
      open1: false,
      title1: '',
      form1: {},
      ifAdmin: false,
      cate_list: [],
      activeTab: 'all'
    }
  },
  created() {
    this.getList()
    this.getCateList()
  },
  computed: {
    ...mapGetters([
      'token'
    ])
  },
  methods: {
    // 跳转
    toUrl(url, event) {
      window.open(url, '_blank')
    },
    // 发布
    publish(row, status) {
      publishNews({ id: row.id, status: status }).then(res => {
        if (res.code === 10000) {
          this.$message({
            message: '发布成功',
            type: 'success'
          })
          this.getList()
        }
      })
    },
    sortChange({ column, prop, order }) {
      this.queryParams.field_order = {}
      const field = prop
      const ord = order

      if (ord == null) {
        delete this.queryParams.field_order
      } else if (ord == 'descending') {
        this.queryParams.field_order[field] = 'desc'
      } else {
        this.queryParams.field_order[field] = 'asc'
      }
      this.getList()
    },
    handleCopy(text, event) {
      clip(text, event)
    },
    newList() {
      this.getList()
    },
    delPort(row) {
      deleteNews(row.id).then(res => {
        console.log(res)
        if (res.code === 10000) {
          this.$message({
            message: '删除成功',
            type: 'success'
          })
          this.getList()
        }
      })
    },

    openAdd(row, type) {
      if (type === '添加') {
        this.open1 = true
        this.title1 = '添加'
        this.form1 = {}
      } else {
        this.open1 = true
        this.title1 = '编辑'
        this.form1 = row
      }
    },
    openCreate() {
      this.open = true
      this.title = '候鸟同步'
      this.form = {}
    },
    resetForm(formName) {
      this.$refs[formName].resetFields()
    },
    handleRemove(file, fileList) {
      console.log(file, fileList)
    },
    handlePictureCardPreview(file) {
      this.dialogImageUrl = file.url
      this.dialogVisible = true
    },
    /** 打开 */
    handleCreate(row, title) {
      const that = this

      if (that.$refs['form']) {
        that.$refs['form'].clearValidate()
      }
      if (that.$refs['upload']) {
        that.$refs['upload'].clearFiles()
      }
      that.fileList = []
      if (row.brand_image) {
        const list = row.brand_image.split(',')
        for (let i = 0; i < list.length; i++) {
          that.fileList.push({ url: list[i] })
        }
      }
      that.form = row
      that.title = title
      that.open = true
    },
    /** 查询清单列表 */
    getList() {
      // 根据当前选中的tab设置查询条件
      if (this.activeTab === 'categorized') {
        this.queryParams.uncategorized = 0; // 已分类：传0
      } else if (this.activeTab === 'uncategorized') {
        this.queryParams.uncategorized = 1; // 未分类：传1
      } else {
        // 全部：不传分类相关参数
        delete this.queryParams.uncategorized;
      }

      console.log(this.queryParams)
      this.loading = true
      newsList(this.queryParams).then(response => {
        console.log(response)
        this.list = response.data
        this.total = response.count
        this.loading = false
      })
    },
    getCateList() {
      const that = this
      this.loading = true
      businesstypeList({ 'page': 1, 'limit': 999999 }).then(response => {
        if (response.code === 10000) {
          // 只保留指定的5个分类
          const includeNames = ['人才招聘', '项目申报', '项目招标', '奖项荣誉', '本地活动']
          that.cate_list = response.data.filter(item => includeNames.includes(item.name))
        }
      })
    },
    uploadSuccess(response, file, fileList) {
      if (response.code === 10000) {
        this.form.brand_image = response.data
      }
    },
    limit(file, fileList) {
      this.$message.warning('只需要上传一张')
    },
    /** 搜索按钮操作 */
    handleQuery() {
      this.queryParams.page = 1
      this.getList()
    },
    /** 重置按钮操作 */
    resetQuery() {
      this.activeTab = 'all'; // 重置时切换到"全部"标签
      this.queryParams = {
        page: 1,
        limit: 10,
        is_jiangsu_zone: 1,
        title: undefined,
        source: undefined,
        search_name: undefined,
        post_time: undefined,
        score: undefined,
        is_rec: undefined,
        publish: undefined,
        cate_id: undefined
      }
      this.handleQuery()
    },
    /** 选中的项 */
    handleSelectionChange(selection) {
      this.ids = selection.map(item => item.id)
      this.multiple = !selection.length
    },
    /** 处理tab切换 */
    handleTabClick() {
      this.queryParams.page = 1;
      this.getList();
    }
  }
}
</script>

